package com.shopping.gateway.filter;

import com.shopping.common.utils.GatewayUtils;
import com.shopping.common.utils.JwtUtils;
import com.shopping.common.utils.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * 鉴权登录
 */
@Component
@Log4j2
public class LoginFilter implements GlobalFilter, Ordered {

    /**
     * 白名单
     */
    private final static List<String> PATHS=new ArrayList<String>(){{
        add("/auth/user/sendSms/**");
        add("/auth/user/login");
        add("/auth/user/addUser");
        add("/system/user/isLogin");
        add("/system/information/goodList");
        add("/system/information/findVoliadSecondSkillGood");
        add("/system/information/findTimeCount");
        add("/system/information/findGoodMore/**");
        add("/system/information/findIsGood");
    }};

    @Autowired
    RedisTemplate<String,Object> redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        //路径 方式
        String path = request.getURI().getPath();
        HttpMethod method = request.getMethod();

        log.info("路径：【{}】，方式：【{}】",path,method);

        //是否为白名单
        if(StringUtils.matches(path,PATHS)){
            return   chain.filter(exchange);
        }

        //生成token
        String token = request.getHeaders().getFirst(JwtUtils.TOKEN);

        //解析token
        String userKey = JwtUtils.getUserKey(token);

        //token不能为空
        if(StringUtils.isEmpty(token)){
            return GatewayUtils.errorResponse(exchange,"token不能为空");
        }

        //token不合法
        try{
            JwtUtils.parseToken(token);
        }catch (Exception e){
            return GatewayUtils.errorResponse(exchange,e.getMessage());
        }

        //token过期或不存在
        System.out.println(redisTemplate.hasKey(JwtUtils.LOGIN_TOKEN_KEY+userKey));
        if(!redisTemplate.hasKey(JwtUtils.LOGIN_TOKEN_KEY+userKey)) {
            return GatewayUtils.errorResponse(exchange, "token过期或不存在");
        }

        //放行

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
